import EventEmitter from 'eventemitter3';
import { TRANSFORM_MODE } from '../const';
import settings from '../settings';
import TransformStatic from './TransformStatic';
import Transform from './Transform';
import Bounds from './Bounds';
import { Rectangle,Point } from '../math';
import { removeItems } from '../utils';
import LayoutStyle from './LayoutStyle'
import { appShared } from '../Application';
// _tempDisplayObjectParent = new DisplayObject();

/**
 * The base class for all objects that are rendered on the screen.
 * This is an abstract class and should not be used on its own rather it should be extended.
 *
 * @class
 * @extends EventEmitter
 * @memberof PIXI
 */
export default class DisplayObject extends EventEmitter
{
    /**
     *
     */
    constructor()
    {
        super();

        const TransformClass = settings.TRANSFORM_MODE === TRANSFORM_MODE.STATIC ? TransformStatic : Transform;

        /**
         * The instance name of the object.
         *
         * @member {string}
         */
        this.name = null;

        /**
         * The array of children of this container.
         *
         * @member {PIXI.DisplayObject[]}
         * @readonly
         */
        this._children = [];

        /**
         * 布局设计样式，用于动态计算位置及大小.
         *
         * @member {PIXI.LayoutStyle}
         */
        this._layout_style = new LayoutStyle();

        /**
         * The width of the sprite (this is initially set by the texture)
         *
         * @private
         * @member {number}
         */
        this._width = 0;

        /**
         * The height of the sprite (this is initially set by the texture)
         *
         * @private
         * @member {number}
         */
        this._height = 0;

        // TODO: need to create Transform from factory
        /**
         * World transform and local transform of this object.
         * This will become read-only later, please do not assign anything there unless you know what are you doing
         *
         * @member {PIXI.TransformBase}
         */
        this.transform = new TransformClass();

        /**
         * The opacity of the object.
         *
         * @member {number}
         */
        this.alpha = 1;

        /**
         * The visibility of the object. If false the object will not be drawn, and
         * the update_transform function will not be called.
         *
         * Only affects recursive calls from parent. You can ask for bounds or call update_transform manually
         *
         * @member {boolean}
         */
        this.visible = true;

        /**
         * Can this object be rendered, if false the object will not be drawn but the update_transform
         * methods will still be called.
         *
         * Only affects recursive calls from parent. You can ask for bounds manually
         *
         * @member {boolean}
         */
        this.renderable = true;

        /**
         * The display object container that contains this display object.
         *
         * @member {PIXI.DisplayObject}
         * @readonly
         */
        this.parent = null;

        /**
         * The multiplied alpha of the displayObject
         *
         * @member {number}
         * @readonly
         */
        this.global_alpha = 1;

        /**
         * The area the filter is applied to. This is used as more of an optimisation
         * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle
         *
         * Also works as an interaction mask
         *
         * @member {PIXI.Rectangle}
         */
        this.filter_area = null;

        this._filters = null;
        this._enabledFilters = null;

        /**
         * The original, cached mask of the object
         *
         * @member {PIXI.Graphics|PIXI.Sprite}
         * @private
         */
        this._mask = null;

        /**
         * If the object has been destroyed via destroy(). If true, it should not be used.
         *
         * @member {boolean}
         * @private
         * @readonly
         */
        this._destroyed = false;

        /**
         * Fired when this DisplayObject is added to a Container.
         *
         * @event PIXI.DisplayObject#added
         * @param {PIXI.DisplayObject} container - The container added to.
         */

        /**
         * Fired when this DisplayObject is removed from a Container.
         *
         * @event PIXI.DisplayObject#removed
         * @param {PIXI.DisplayObject} container - The container removed from.
         */
        
        /**
         * The dirty state of this object.
         *
         * @member {boolean}
         */
        this._dirty = true;
    }

    /**
     * The dirty state of this object.
     *
     * @member {boolean}
     */
    get dirty(){ return this._dirty;}
    set dirty(v){
        this._dirty = v;
    }

    /**
     * 布局设计样式，该样式用于设置DisplayObject的尺寸及位置关系
     * @member {PIXI.LayoutStyle}
     */
    get layout_style()
    {
        return this._layout_style;
    }
    set layout_style(v){
        if(!(v instanceof LayoutStyle))
            throw 'invalid layout style type!!';
        this._layout_style = v;
        this._layout_style.dirty = true;
    }

    /**
     * 更新自身及所有子节点的布局信息
     * @private
     */
    _update_layout(){
        var pw = this.parent?this.parent.width:appShared.renderer.width;
        var ph = this.parent?this.parent.height:appShared.renderer.height;
        if(this._layout_style.offset_dirty){
            this._layout_style.update_offset(this.x,this.y,this.width,this.height,pw,ph);
        }
        var rt = this._layout_style.get_layout(pw,ph);
        this.x = rt.x;
        this.y = rt.y;
        this.width = rt.width;
        this.height = rt.height;
        this._layout_style.dirty = false;
        this._layout_style.offset_dirty = false;
        for(var i = 0;i < this._children.length;i++){
            this._children[i]._update_layout();
        }
    }

    /**
     * Tests if a point is inside this displayObject
     *
     * @param {PIXI.Point} point - the point to test
     * @return {boolean} the result of the test
     */
    contains_point(point)
    {
        var rt = get_local_bounds();
        return rt.contains_point(this.global_transform.applyInverse(point));
    }

    /**
     * Retrieves the bounds of the displayObject as a rectangle object.
     *
     * @param {boolean} skipUpdate - setting to true will stop the transforms of the scene graph from
     *  being updated. This means the calculation returned MAY be out of date BUT will give you a
     *  nice performance boost
     * @param {PIXI.Rectangle} rect - Optional rectangle to store the result of the bounds calculation
     * @return {PIXI.Rectangle} the rectangular bounding area
     */
    get_bounds(skipUpdate, rect)
    {
        rect = this.get_local_bounds(rect);
        var lt=new Point(rect.x,rect.y);
        this.global_transform.apply(lt,lt,skipUpdate);
        var rb=new Point(rect.right,rect.bottom);
        this.global_transform.apply(rb,rb,skipUpdate);
        rect.x = lt.x;rect.y=lt.y;
        rect.width = rb.x-rect.x;rect.height=rb.y-rect.y; 
        return rect;
    }

    /**
     * Retrieves the local bounds of the displayObject as a rectangle object
     *
     * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation
     * @return {PIXI.Rectangle} the rectangular bounding area
     */
    get_local_bounds(rect)
    {
        if(!skipUpdate && (this.dirty||this._layout_style.dirty)){
            this.update_transform();
        }
        return this._layout_style.get_layout(this.parent?this.parent.width:appShared.renderer.width,this.parent?this.parent.height:appShared.renderer.height,rect);
    }

    /**
     * Calculates the global position of the display object
     *
     * @param {PIXI.Point} position - The world origin to calculate from
     * @param {PIXI.Point} [point] - A Point object in which to store the value, optional
     *  (otherwise will create a new Point)
     * @param {boolean} [skipUpdate=false] - Should we skip the update transform.
     * @return {PIXI.Point} A point object representing the position of this object
     */
    to_global(position, point, skipUpdate = false)
    {
        if(!skipUpdate && (this.dirty||this._layout_style.dirty)){
            this.update_transform();
        }

        // don't need to update the lot
        return this.global_transform.apply(position, point);
    }

    /**
     * Calculates the local position of the display object relative to another point
     *
     * @param {PIXI.Point} position - The world origin to calculate from
     * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from
     * @param {PIXI.Point} [point] - A Point object in which to store the value, optional
     *  (otherwise will create a new Point)
     * @param {boolean} [skipUpdate=false] - Should we skip the update transform
     * @return {PIXI.Point} A point object representing the position of this object
     */
    to_local(position, from, point, skipUpdate)
    {
        if (from)
        {
            position = from.to_global(position, point, skipUpdate);
        }

        if(!skipUpdate && (this.dirty||this._layout_style.dirty)){
            this.update_transform();
        }

        // simply apply the matrix..
        return this.global_transform.applyInverse(position, point);
    }

    /**
     * Set the parent Container of this DisplayObject
     *
     * @param {PIXI.DisplayObject} container - The Container to add this DisplayObject to
     * @return {PIXI.DisplayObject} The Container that this DisplayObject was added to
     */
    set_parent(container)
    {
        if (!container || !container.add_child)
        {
            throw new Error('set_parent: Argument must be a DisplayObject');
        }

        container.add_child(this);

        return container;
    }

    /**
     * Convenience function to set the position, scale, skew and pivot at once.
     *
     * @param {number} [x=0] - The X position
     * @param {number} [y=0] - The Y position
     * @param {number} [scaleX=1] - The X scale value
     * @param {number} [scaleY=1] - The Y scale value
     * @param {number} [rotation=0] - The rotation
     * @param {number} [skewX=0] - The X skew value
     * @param {number} [skewY=0] - The Y skew value
     * @param {number} [pivotX=0] - The X pivot value
     * @param {number} [pivotY=0] - The Y pivot value
     * @return {PIXI.DisplayObject} The DisplayObject instance
     */
    set_transform(x = 0, y = 0, scaleX = 1, scaleY = 1, rotation = 0, skewX = 0, skewY = 0, pivotX = 0, pivotY = 0)
    {
        this.position.x = x;
        this.position.y = y;
        this.scale.x = !scaleX ? 1 : scaleX;
        this.scale.y = !scaleY ? 1 : scaleY;
        this.rotation = rotation;
        this.skew.x = skewX;
        this.skew.y = skewY;
        this.pivot.x = pivotX;
        this.pivot.y = pivotY;

        this._dirty = true;
        this._layout_style.offset_dirty = true;
        return this;
    }

    /**
     * The position of the displayObject on the x axis relative to the local coordinates of the parent.
     * An alias to position.x
     *
     * @member {number}
     */
    get x()
    {
        if(this._layout_style.dirty){
            this._update_layout();
        }
        return this.position.x;
    }

    set x(value) // eslint-disable-line require-jsdoc
    {
        this._dirty = true;
        this.transform.position.x = value;
        this._layout_style.offset_dirty = true;
    }

    /**
     * The position of the displayObject on the y axis relative to the local coordinates of the parent.
     * An alias to position.y
     *
     * @member {number}
     */
    get y()
    {
        if(this._layout_style.dirty){
            this._update_layout();
        }
        return this.position.y;
    }

    set y(value) // eslint-disable-line require-jsdoc
    {
        this._dirty = true;
        this.transform.position.y = value;
        this._layout_style.offset_dirty = true;
    }

    /**
     * Current transform of the object based on world (parent) factors
     *
     * @member {PIXI.Matrix}
     * @readonly
     */
    get global_transform()
    {
        if(this.dirty||this._layout_style.dirty){
            this.update_transform();
        }
        return this.transform.global_transform;
    }

    /**
     * Current transform of the object based on local factors: position, scale, other stuff
     *
     * @member {PIXI.Matrix}
     * @readonly
     */
    get local_transform()
    {
        if(this._layout_style.dirty){
            this.update_transform();
        }
        return this.transform.local_transform;
    }

    /**
     * The coordinate of the object relative to the local coordinates of the parent.
     * Assignment by value since pixi-v4.
     *
     * @member {PIXI.Point|PIXI.ObservablePoint}
     */
    get position()
    {
        if(this._layout_style.dirty){
            this._update_layout();
        }
        return this.transform.position;
    }

    set position(value) // eslint-disable-line require-jsdoc
    {
        this._dirty = true;
        this.transform.position.copy(value);
        this._layout_style.offset_dirty = true;
    }

    /**
     * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot.
     *
     * @memberof PIXI.DisplayObject#
     *  being updated. This means the calculation returned MAY be out of date BUT will give you a
     *  nice performance boost
     * @return {Point} The updated point
     */
    get global_position()
    {
        if(this.dirty||this._layout_style.dirty){
            this.update_transform();
        }
        var point = new Point()
        if (this.parent)
        {
            this.parent.to_global(this.position, point, false);
        }
        else
        {
            point.x = this.position.x;
            point.y = this.position.y;
        }

        return point;
    };

    /**
     * The scale factor of the object.
     * Assignment by value since pixi-v4.
     *
     * @member {PIXI.Point|PIXI.ObservablePoint}
     */
    get scale()
    {
        return this.transform.scale;
    }

    set scale(value) // eslint-disable-line require-jsdoc
    {
        this._dirty = true;
        this.transform.scale.copy(value);
        this._layout_style.dirty = true;
    }

    /**
     * The pivot point of the displayObject that it rotates around
     * Assignment by value since pixi-v4.
     *
     * @member {PIXI.Point|PIXI.ObservablePoint}
     */
    get pivot()
    {
        return this.transform.pivot;
    }

    set pivot(value) // eslint-disable-line require-jsdoc
    {
        this._dirty = true;
        this.transform.pivot.copy(value);
        this._layout_style.dirty = true;
    }

    /**
     * The skew factor for the object in radians.
     * Assignment by value since pixi-v4.
     *
     * @member {PIXI.ObservablePoint}
     */
    get skew()
    {
        return this.transform.skew;
    }

    set skew(value) // eslint-disable-line require-jsdoc
    {
        this._dirty = true;
        this.transform.skew.copy(value);
        this._layout_style.dirty = true;
    }

    /**
     * The rotation of the object in radians.
     *
     * @member {number}
     */
    get rotation()
    {
        return this.transform.rotation;
    }

    set rotation(value) // eslint-disable-line require-jsdoc
    {
        this._dirty = true;
        this.transform.rotation = value;
        this._layout_style.dirty = true;
    }

    /**
     * Indicates if the object is globally visible.
     *
     * @member {boolean}
     * @readonly
     */
    get real_visible()
    {
        let item = this;

        do
        {
            if (!item.visible)
            {
                return false;
            }

            item = item.parent;
        } while (item);

        return true;
    }

    /**
     * Sets a mask for the displayObject. A mask is an object that limits the visibility of an
     * object to the shape of the mask applied to it. In PIXI a regular mask must be a
     * PIXI.Graphics or a PIXI.Sprite object. This allows for much faster masking in canvas as it
     * utilises shape clipping. To remove a mask, set this property to null.
     *
     * @todo For the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask.
     *
     * @member {PIXI.Graphics|PIXI.Sprite}
     */
    get mask()
    {
        return this._mask;
    }

    set mask(value) // eslint-disable-line require-jsdoc
    {
        if (this._mask)
        {
            this._mask.renderable = true;
        }

        this._mask = value;

        if (this._mask)
        {
            this._mask.renderable = false;
        }
    }

    /**
     * Sets the filters for the displayObject.
     * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer.
     * To remove filters simply set this property to 'null'
     *
     * @member {PIXI.Filter[]}
     */
    get filters()
    {
        return this._filters && this._filters.slice();
    }

    set filters(value) // eslint-disable-line require-jsdoc
    {
        this._filters = value && value.slice();
    }

    /**
     * Overridable method that can be used by Container subclasses whenever the children array is modified
     *
     * @private
     */
    _on_children_changed()
    {
        /* empty */
    }

    /**
     * 获取子节点数量
     * @member {number}
     * @readonly
     */
    get children_num(){ return this._children.length;}

    /**
     * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown
     *
     * @param {PIXI.DisplayObject} child - The child to add
     * @param {number} index - The index to place the child in,append end if is invoid index(index<0||index>=length)
     * @return {PIXI.DisplayObject} The child that was added.
     */
    add_child(child, index)
    {
        if (child.parent)
        {
            child.parent.remove_child(child);
        }

        child.parent = this;
        // ensure child transform will be recalculated
        child.transform._parentID = -1;

        if (arguments.length==1||index < 0 || index >= this._children.length)
        {
            this._children.push(child);
        }else{
            this._children.splice(index, 0, child);
        }

        // TODO - lets either do all callbacks or all events.. not both!
        this._on_children_changed(index);
        child.emit('added', this);

        return child;
    }

    /**
     * Swaps the position of 2 Display Objects within this container.
     *
     * @param {PIXI.DisplayObject} child - First display object to swap
     * @param {PIXI.DisplayObject} child2 - Second display object to swap
     */
    swap_child(child, child2)
    {
        if (child === child2)
        {
            return;
        }

        const index1 = this.get_child_index(child);
        const index2 = this.get_child_index(child2);

        this._children[index1] = child2;
        this._children[index2] = child;
        this._on_children_changed(index1 < index2 ? index1 : index2);
    }

    /**
     * Returns the index position of a child DisplayObject instance
     *
     * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify
     * @return {number} The index position of the child display object to identify
     */
    get_child_index(child)
    {
        const index = this._children.indexOf(child);

        if (index === -1)
        {
            throw new Error('The supplied DisplayObject must be a child of the caller');
        }

        return index;
    }

    /**
     * Changes the position of an existing child in the display object container
     *
     * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number
     * @param {number} index - The resulting index number for the child display object
     */
    set_child_index(child, index)
    {
        if (index < 0 || index >= this._children.length)
        {
            throw new Error('The supplied index is out of bounds');
        }

        const currentIndex = this.get_child_index(child);

        removeItems(this._children, currentIndex, 1); // remove from old position
        this._children.splice(index, 0, child); // add at new position

        this._on_children_changed(index);
    }

    /**
     * Returns the child at the specified index
     *
     * @param {number} index - The index to get the child at
     * @return {PIXI.DisplayObject} The child at the given index, if any.
     */
    get_child_at(index)
    {
        if (index < 0 || index >= this._children.length)
        {
            throw new Error(`get_child_at: Index (${index}) does not exist.`);
        }

        return this._children[index];
    }
    
    __get_child_by_name(n){
        for (var i = this._children.length - 1; i >= 0; i--) {
          if (n == this._children[i].name) return this._children[i]
        }
        return this.name == n ? this : null
    }

    /**
     * Returns the display object in the container
     *
     * @param {string} name - object name,can use xxx/yyy/name
     * @return {PIXI.DisplayObject} The child with the specified name.
     */
    get_child(name)
    {
        var ns = n.split("/")
        var c = this
        if(ns.length>1){
            for(var i in ns){
                var cc = c.__get_child_by_name(ns[i])
                if(cc == null) return null
                c = cc
            }
        }else{
            for (var i in this._children) {
                if (name == this._children[i].name) 
                    return this._children[i]
                var c = this._children[i].get_child(name)
                if(c) return c
            }
        }
        return c
    }

    /**
     * Removes one or more _children from the container.
     *
     * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to remove
     * @return {PIXI.DisplayObject} The first child that was removed.
     */
    remove_child(child)
    {
        const argumentsLength = arguments.length;

        // if there is only one argument we can bypass looping through the them
        if (argumentsLength > 1)
        {
            // loop through the arguments property and add all _children
            // use it the right way (.length and [i]) so that this function can still be optimised by JS runtimes
            for (let i = 0; i < argumentsLength; i++)
            {
                this.remove_child(arguments[i]);
            }
        }
        else
        {
            const index = this._children.indexOf(child);

            if (index === -1) return null;

            child.parent = null;
            // ensure child transform will be recalculated
            child.transform._parentID = -1;
            removeItems(this._children, index, 1);

            // TODO - lets either do all callbacks or all events.. not both!
            this._on_children_changed(index);
            child.emit('removed', this);
        }

        return child;
    }

    /**
     * Removes a child from the specified index position.
     *
     * @param {number} index - The index to get the child from
     * @return {PIXI.DisplayObject} The child that was removed.
     */
    remove_child_at(index)
    {
        const child = this.get_child_at(index);

        // ensure child transform will be recalculated..
        child.parent = null;
        child.transform._parentID = -1;
        removeItems(this._children, index, 1);

        // TODO - lets either do all callbacks or all events.. not both!
        this._on_children_changed(index);
        child.emit('removed', this);

        return child;
    }

    /**
     * Removes all _children from this container that are within the begin and end indexes.
     *
     * @param {number} [beginIndex=0] - The beginning position.
     * @param {number} [endIndex=this._children.length] - The ending position. Default value is size of the container.
     * @returns {DisplayObject[]} List of removed _children
     */
    remove_children(beginIndex = 0, endIndex)
    {
        const begin = beginIndex;
        const end = typeof endIndex === 'number' ? endIndex : this._children.length;
        const range = end - begin;
        let removed;

        if (range > 0 && range <= end)
        {
            removed = this._children.splice(begin, range);

            for (let i = 0; i < removed.length; ++i)
            {
                removed[i].parent = null;
                if (removed[i].transform)
                {
                    removed[i].transform._parentID = -1;
                }
            }

            this._on_children_changed(beginIndex);

            for (let i = 0; i < removed.length; ++i)
            {
                removed[i].emit('removed', this);
            }

            return removed;
        }
        else if (range === 0 && this._children.length === 0)
        {
            return [];
        }

        throw new RangeError('remove_children: numeric values are outside the acceptable range.');
    }

    /**
     * Updates the transform on all _children of this container for rendering
     */
    update_transform()
    {
        this._dirty = false;
        if(this._layout_style.offset_dirty||this._layout_style.dirty){
            this._update_layout();
        }

        if(this.parent)
            this.transform.update_transform(this.parent.transform);

        // TODO: check render flags, how to process stuff here
        this.global_alpha = this.parent?this.alpha * this.parent.global_alpha:1;

        for (let i = 0, j = this._children.length; i < j; ++i)
        {
            const child = this._children[i];

            if (child.visible)
            {
                child.update_transform();
            }
        }
    }

    /**
     * Renders the object using the WebGL renderer
     *
     * @param {PIXI.WebGLRenderer} renderer - The renderer
     */
    draw_webgl(renderer)
    {
        // if the object is not visible or the alpha is 0 then no need to render this element
        if (!this.visible || this.global_alpha <= 0 || !this.renderable)
        {
            return;
        }

        if(this.dirty||this._layout_style.dirty){
            this.update_transform();
        }
        
        // do a quick check to see if this element has a mask or a filter.
        if (this._mask || this._filters)
        {
            this._on_draw_advance_webgl(renderer);
        }
        else
        {
            this._on_draw_webgl(renderer);

            // simple render _children!
            for (let i = 0, j = this._children.length; i < j; ++i)
            {
                this._children[i].draw_webgl(renderer);
            }
        }
    }

    /**
     * Render the object using the WebGL renderer and advanced features.
     *
     * @private
     * @param {PIXI.WebGLRenderer} renderer - The renderer
     */
    _on_draw_advance_webgl(renderer)
    {
        renderer.flush();

        const filters = this._filters;
        const mask = this._mask;

        // push filter first as we need to ensure the stencil buffer is correct for any masking
        if (filters)
        {
            if (!this._enabledFilters)
            {
                this._enabledFilters = [];
            }

            this._enabledFilters.length = 0;

            for (let i = 0; i < filters.length; i++)
            {
                if (filters[i].enabled)
                {
                    this._enabledFilters.push(filters[i]);
                }
            }

            if (this._enabledFilters.length)
            {
                renderer.filterManager.pushFilter(this, this._enabledFilters);
            }
        }

        if (mask)
        {
            renderer.maskManager.pushMask(this, this._mask);
        }

        // add this object to the batch, only rendered if it has a texture.
        this._on_draw_webgl(renderer);

        // now loop through the _children and make sure they get rendered
        for (let i = 0, j = this._children.length; i < j; i++)
        {
            this._children[i].draw_webgl(renderer);
        }

        renderer.flush();

        if (mask)
        {
            renderer.maskManager.popMask(this, this._mask);
        }

        if (filters && this._enabledFilters && this._enabledFilters.length)
        {
            renderer.filterManager.popFilter();
        }
    }

    /**
     * To be overridden by the subclasses.
     *
     * @private
     * @param {PIXI.WebGLRenderer} renderer - The renderer
     */
    _on_draw_webgl(renderer) // eslint-disable-line no-unused-vars
    {
        // this is where content itself gets rendered...
    }

    /**
     * To be overridden by the subclass
     *
     * @private
     * @param {PIXI.CanvasRenderer} renderer - The renderer
     */
    _on_draw_canvas(renderer) // eslint-disable-line no-unused-vars
    {
        // this is where content itself gets rendered...
    }

    /**
     * Renders the object using the Canvas renderer
     *
     * @param {PIXI.CanvasRenderer} renderer - The renderer
     */
    draw_canvas(renderer)
    {
        // if not visible or the alpha is 0 then no need to render this
        if (!this.visible || this.global_alpha <= 0 || !this.renderable)
        {
            return;
        }

        if(this.dirty||this._layout_style.dirty){
            this.update_transform();
        }

        if (this._mask)
        {
            renderer.maskManager.pushMask(this._mask);
        }

        this._on_draw_canvas(renderer);
        for (let i = 0, j = this._children.length; i < j; ++i)
        {
            this._children[i].draw_canvas(renderer);
        }

        if (this._mask)
        {
            renderer.maskManager.popMask(renderer);
        }
    }

    /**
     * Removes all internal references and listeners as well as removes _children from the display list.
     * Do not use a Container after calling `destroy`.
     *
     * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
     *  have been set to that value
     * @param {boolean} [options._children=false] - if set to true, all the _children will have their destroy
     *  method called as well. 'options' will be passed on to those calls.
     * @param {boolean} [options.texture=false] - Only used for child Sprites if options._children is set to true
     *  Should it destroy the texture of the child sprite
     * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options._children is set to true
     *  Should it destroy the base texture of the child sprite
     */
    destroy(options)
    {
        this.removeAllListeners();
        if (this.parent)
        {
            this.parent.remove_child(this);
        }
        this.transform = null;

        this.parent = null;

        this._bounds = null;
        this._currentBounds = null;
        this._mask = null;

        this.filter_area = null;

        this.enabled = false;
        this.children_enabled = false;

        this._destroyed = true;

        const destroyChildren = typeof options === 'boolean' ? options : options && options._children;

        const oldChildren = this.remove_children(0, this._children.length);

        if (destroyChildren)
        {
            for (let i = 0; i < oldChildren.length; ++i)
            {
                oldChildren[i].destroy(options);
            }
        }
    }

    /**
     * The width of the Container, setting this will actually modify the scale to achieve the value set
     *
     * @member {number}
     */
    get width()
    {
        return this._width;
    }

    set width(value) // eslint-disable-line require-jsdoc
    {
        this._layout_style.width = this._width = value;
        this._layout_style.dirty = true;
    }

    /**
     * The height of the Container, setting this will actually modify the scale to achieve the value set
     *
     * @member {number}
     */
    get height()
    {
        return this._height;
    }

    set height(value) // eslint-disable-line require-jsdoc
    {
        this._layout_style.height = this._height = value;
        this._layout_style.dirty = true;
    }
}

// performance increase to avoid using call.. (10x faster)
DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.update_transform;
